from flask import Blueprint, render_template, request
from applications.common.utils.validate import xss_escape
from applications.common.helper import ModelFilter
from applications.models import History
from applications.common.curd import model_to_dicts
from applications.common.utils.http import table_api, fail_api, success_api
from applications.schemas import HistoryOutSchema
from applications.extensions import db
from flask_login import login_required, current_user
from applications.common.utils.rights import authorize


pest_history = Blueprint('PestHistory', __name__, url_prefix='/')


# 图片识别记录的视图
@pest_history.get('/pest_history')
def main():
    return render_template('admin/pest/pest_history.html')


# 管理员查询记录的查询接口
@pest_history.get('/pest_history/info')
@authorize("history:admin", log=True)
# 获取请求参数
def data():
    # 查询参数
    disease_name = xss_escape(request.args.get('disease_name', type=str))
    # 查询参数构造
    mf = ModelFilter()
    if disease_name:
        mf.contains(field_name="disease_name", value=disease_name)
    # orm查询
    # 使用分页获取data需要.items
    history_info = History.query.filter(mf.get_filter(model=History)).layui_paginate()
    count = history_info.total
    # 返回api
    return table_api(data=model_to_dicts(schema=HistoryOutSchema, data=history_info.items), count=count)


# 普通用户查询自己记录的查询接口
@pest_history.get('/pest_history/user_info')
@authorize("history:user", log=True)
# 获取请求参数
def mydata():
    # 查询参数
    disease_name = xss_escape(request.args.get('disease_name', type=str))
    # 查询参数构造
    mf = ModelFilter()

    # 登录的用户名
    user_name = current_user.realname

    if disease_name:
        mf.contains(field_name="disease_name", value=disease_name)
    # orm查询
    # 使用分页获取data需要.items
    history_info = History.query.filter(mf.get_filter(model=History),
                                        History.user_id.like("%" + user_name + "%")).layui_paginate()
    count = history_info.total
    # 返回api
    return table_api(data=model_to_dicts(schema=HistoryOutSchema, data=history_info.items), count=count)


# 删除
@pest_history.delete('/pest_history/remove/<int:history_id>')
# @authorize("history:remove", log=True)
def delete(history_id):

    res = History.query.filter_by(history_id=history_id).delete()
    db.session.commit()
    if not res:
        return fail_api(msg="删除失败")
    return success_api(msg="删除成功")


# 批量删除
@pest_history.delete('/pest_history/batchRemove')
# @authorize("history:remove", log=True)
def batch_remove():
    ids = request.form.getlist('ids[]')
    for history_id in ids:
        res = History.query.filter_by(history_id=history_id).delete()
        db.session.commit()
    return success_api(msg="批量删除成功")
